#include "message.hpp"
#include "net.hpp"
#include "dispatcher.hpp"
#include <muduo/base/Logging.h>

void onRpcRequest(const RPC::BaseConnection::Ptr &conn, RPC::RpcRequest::Ptr &msg)
{
    INFO_LOG("有新的RPC请求到来了！");
    std::string body = msg->serialize();
    std::cout << body << std::endl;
    auto rpc_res = RPC::MessageFactory::create<RPC::RpcResponse>();
    rpc_res->setId("111111");
    rpc_res->setType(RPC::MType::RES_RPC);
    rpc_res->setRCode(RPC::RCode::RCODE_OK);
    rpc_res->setResult(33);
    conn->send(rpc_res);
}

void onRpcResponse(const RPC::BaseConnection::Ptr &conn, RPC::RpcResponse::Ptr &msg)
{
    INFO_LOG("有新的RPC应答到来了！");
    std::string body = msg->serialize();
    std::cout << body << std::endl;
}

// using Requsetpointer = std::function<void(const RPC::BaseConnection::Ptr &, RPC::RpcRequest::Ptr &)>;
// using rpcRequsetpointer = std::function<void(const RPC::MType &type , const Requsetpointer &)>;
int main()
{
    // 取消muduo库的普通日志
    muduo::Logger::setLogLevel(muduo::Logger::FATAL);
    auto server = RPC::ServerFactory::create(9090);

    RPC::Dispatcher dispatcher;
    dispatcher.registerCallback<RPC::RpcRequest>(RPC::MType::REQ_RPC, onRpcRequest);
    dispatcher.registerCallback<RPC::RpcResponse>(RPC::MType::RES_RPC, onRpcResponse);
    auto onMessage = std::bind(&RPC::Dispatcher::onMessage, &dispatcher, 
    std::placeholders::_1, std::placeholders::_2);
    server->setMessageCallback(onMessage);

    server->start();
    return 0;
}